import { defineStore } from 'pinia'
import { accountLoginRequest, getUserInfoById, getUserMenusByRoleId } from '@/service/login/login'
import type { IAccount } from '@/types/index'
import { localcache } from '@/utils/cache'
import router from '@/router'
import { LOGIN_TOKEN } from '@/global/constances'
import { mapMenusToRoutes } from '@/utils/map-menus'
import useMainStore from '../main/main'
// const LOGIN_TOKEN = 'login/token'
interface ILoginState {
  token: string
  userInfo: any
  userMenus: any //存放角色权限菜单
}
const useLoginStore = defineStore('login', {
  state: (): ILoginState => ({
    token: '',
    userInfo: {}, // 存放用户信息
    userMenus: [] //存放角色权限菜单
  }),
  actions: {
    async loginAccountAction(account: IAccount) {
      // 请求token
      const { data: res } = await accountLoginRequest(account)

      const id = res.id
      // const name = res.name
      this.token = res.token
      // 因为第29行代码要用到token中携带的id，所以必须要提前把token存起来，才能供后面的正常运行
      localcache.setCache(LOGIN_TOKEN, this.token)
      // 请求用户信息
      const userInfoResult = await getUserInfoById(id)
      const userInfo = userInfoResult.data
      this.userInfo = userInfo
      // 根据角色请求权限（菜单信息）
      const userMenusResult = await getUserMenusByRoleId(this.userInfo.role.id)
      this.userMenus = userMenusResult.data

      // 进行本地缓存

      localcache.setCache('userInfo', userInfo)
      localcache.setCache('userMenus', this.userMenus)
      // 请求所有的roles和department数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
      // 动态加载菜单路由  映射文件封装为工具函数utils/map-menu

      const routes = mapMenusToRoutes(this.userMenus)
      routes.forEach((route) => router.addRoute('main', route))
      // 页面跳转
      router.push('/main')
    },
    // 加载本地数据的action  获取token，userinfo和usermenus统一来做
    loadLocalCacheAction() {
      // 用户刷新 默认加载数据
      const token = localcache.getCache(LOGIN_TOKEN)
      const userInfo = localcache.getCache('userInfo')
      const userMenus = localcache.getCache('userMenus')
      this.userMenus = userMenus
      // 判断三个同时有值的时候才会进行赋值   说明此时已经登录
      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus
        //刷新后再次 请求所有的最新的roles和department数据
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()
        // 动态添加路由
        // 动态加载菜单路由  映射文件封装为工具函数utils/map-menu
        const routes = mapMenusToRoutes(userMenus)
        routes.forEach((route) => router.addRoute('main', route))
      }
    }
  }
})
export default useLoginStore
